<template>
  <div class="contentSrc">
    <div id="userMyPage">
      <a-layout style="height: 100vh">
        <a-layout-header class="header">
          <GlobalHeader />
        </a-layout-header>
        <a-layout-content class="content">
          <a-form
            :model="formState"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item label="头像">
              <a-avatar
                :size="avatarSize"
                :image-url="formState.userAvatar"
                :style="{ marginRight: '100px' }"
              />
            </a-form-item>
            <a-form-item label="账号" prop="userAccount">
              <a-input v-model="formState.userAccount" :disabled="!editMode" />
            </a-form-item>
            <a-form-item label="用户名" prop="userName">
              <a-input v-model="formState.userName" :disabled="!editMode" />
            </a-form-item>
            <a-form-item label="用户简介" prop="userProfile">
              <a-textarea
                v-model="formState.userProfile"
                :disabled="!editMode"
                :rows="4"
              />
            </a-form-item>
            <a-form-item label="创建时间" prop="createTime">
              <span>{{ createTimeFormatted }}</span>
            </a-form-item>
            <a-form-item v-if="editMode" :wrapper-col="{ offset: 4, span: 16 }">
              <a-button type="primary" @click="saveChanges">保存更改</a-button>
              <a-button style="margin-left: 8px" @click="cancelEdit"
                >取消</a-button
              >
            </a-form-item>
            <a-form-item
              v-else-if="!editMode"
              :wrapper-col="{ offset: 4, span: 16 }"
            >
              <div v-if="!editMode && !loading && !error">
                <a-button
                  @click="toggleEditMode"
                  type="primary"
                  style="margin-bottom: 16px; margin-right: 8px"
                  >编辑信息</a-button
                >
                <!--                <a-button-->
                <!--                  style="margin-bottom: 16px; margin-right: 8px"-->
                <!--                  @click="changePassword"-->
                <!--                  >修改密码</a-button-->
                <!--                >-->
                <a-button type="danger" @click="logout">退出登录</a-button>
              </div>
            </a-form-item>
            <div v-else-if="loading">
              <a-skeleton active avatar paragraph title :loading="true" />
            </div>
            <div v-else-if="error">
              <p>无法加载用户信息，请稍后重试。</p>
            </div>
          </a-form>
        </a-layout-content>
        <a-layout-footer class="footer">
          <a href="https://gitee.com/linsheng0116" target="_blank">By 林笙</a>
        </a-layout-footer>
      </a-layout>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, computed } from "vue";
import GlobalHeader from "@/components/GlobalHeader.vue";
import dayjs from "dayjs";
import {
  getLoginUserUsingGet,
  editUserUsingPost,
  userLogoutUsingPost,
} from "@/api/userController";

// 用户信息响应式对象
const userInfo = ref(null);
const formState = ref({
  userAccount: "",
  userName: "",
  userProfile: "",
  userAvatar: "",
  createTime: "",
  updateTime: "",
});
const loading = ref(true);
const error = ref(false);
const editMode = ref(false);

// 计算属性判断用户信息是否已加载
const createTimeFormatted = computed(() => {
  return formState.value.createTime
    ? dayjs(formState.value.createTime).format("YYYY-MM-DD")
    : "";
});

// 用户头像大小
const avatarSize = 100;

// 在组件挂载时获取用户信息
onMounted(async () => {
  try {
    const response = await getLoginUserUsingGet();
    if (response.data.code === 0 && response.data.data) {
      Object.assign(formState.value, response.data.data);
      userInfo.value = response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    error.value = true;
  } finally {
    loading.value = false;
  }
});

const toggleEditMode = () => {
  editMode.value = !editMode.value;
};

const saveChanges = async () => {
  try {
    const body = {
      userAccount: formState.value.userAccount,
      userName: formState.value.userName,
      userProfile: formState.value.userProfile,
    };
    const response = await editUserUsingPost(body);
    if (response.data.code === 0) {
      editMode.value = false;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error("保存用户信息失败:", error);
  }
};

const cancelEdit = () => {
  Object.assign(formState.value, userInfo.value);
  editMode.value = false;
};

const logout = async () => {
  try {
    // 清除浏览器存储
    localStorage.clear();
    sessionStorage.clear();
    document.cookie.split(";").forEach((cookie) => {
      document.cookie = cookie
        .replace(/^ +/, "")
        .replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`);
    });

    // 执行后端注销操作
    const response = await userLogoutUsingPost();
    if (response.data.code === 0) {
      // 重新定向到登录页面或其他操作
      window.location.href = "/"; // 假设登录页面的路径为 /login
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error("退出登录失败:", error);
  }
};
</script>
<style scoped>
#userMyPage .header {
  box-shadow: 0 1px 5px #eee;
}

.contentSrc {
  background-image: url("@/assets/logo2.jpg");
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}

#userMyPage .content {
  box-sizing: border-box;
  width: 100%;
  max-width: 1200px;
  height: 800px;
  margin: 0 auto 28px;
  padding: 20px;
  background-image: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
}

.footer {
  padding: 16px;
  text-align: center;
  text-decoration: none;
  background: #efefef;
}

/* 如果选择直接控制单个按钮间距，则不需要上面的 .button-group 容器 */
a-button {
  margin-right: 8px;
}
</style>
